import { Component, OnInit, ViewChild } from '@angular/core';

import { NzTreeFlatDataSource, NzTreeFlattener } from 'ng-zorro-antd/tree-view';
import {
  CollectionViewer,
  DataSource,
  SelectionChange,
  SelectionModel,
} from '@angular/cdk/collections';
import { FlatTreeControl, TreeControl } from '@angular/cdk/tree';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { EmployeeSearchComponent } from 'src/app/share/employee-search/employee-search.component';
import { RoleSearchComponent } from 'src/app/share/role-search/role-search.component';
import { EmployeeOrganizationRole } from 'src/app/domain/employee-organization-role';
import { OrganizationSearchComponent } from 'src/app/share/organization-search/organization-search.component';
import { Observable, of, BehaviorSubject, merge, zip, concat } from 'rxjs';
import { tap, map, switchMap } from 'rxjs/operators';
import { LevelSearchComponent } from 'src/app/share/level-search/level-search.component';
import { SetModelPermissionComponent } from 'src/app/share/set-model-permission/set-model-permission.component';
import { SetDataPermissionComponent } from 'src/app/share/set-data-permission/set-data-permission.component';
import {
  Employee,
  EmployeeService,
  JoblevelService,
  OrganizationService,
  RoleService,
} from 'sparrow-permission-lib';
import { FlatNode } from 'src/app/domain/flat-node';
import { DynamicDataSourceForNzTreeService } from 'src/app/service/dynamic-data-source-for-nz-tree.service';
import { NzTreeCommonService } from 'src/app/service/nz-tree-common.service';
import { NzTreeGetChildren } from 'src/app/service/nz-tree-get-children';
import { NzTreeGetLevelChildrenService } from 'src/app/service/nz-tree-get-level-children.service';
import { NzTreeGetEmployeeChildrenService } from 'src/app/service/nz-tree-get-employee-children.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css'],
})
export class EmployeeComponent implements OnInit {
  modelName?: string;
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private employeeService: EmployeeService,
    private orgService: OrganizationService,
    private levelService: JoblevelService,
    private roleService: RoleService
  ) {}
  dataSource: any;
  hasChild = (_: number, node: FlatNode) => node.expandable;
  treeService: NzTreeCommonService = new NzTreeCommonService();

  ngOnInit(): void {
    let getChildrenService: NzTreeGetChildren =
      new NzTreeGetEmployeeChildrenService(
        this.employeeService,
        this.orgService
      );
    getChildrenService
      .getChildren({
        id: 'root',
        label: 'root',
        level: -1,
        expandable: true,
        type: 'ORG',
      })
      .subscribe(
        (res) => {
          this.dataSource = new DynamicDataSourceForNzTreeService(
            this.treeService.treeControl,
            res,
            getChildrenService
          );
        },
        (error) => {
          this.message.error('初始化失败！' + error);
        }
      );
  }

  selectedEmployee: any;
  onItemSelect(node: FlatNode): void {
    this.treeService.selectListSelection.toggle(node);
    console.log(node);
    const employee$ = this.employeeService.get8(node.id).pipe(
      switchMap((employee: any) =>
        this.orgService.get4(employee.organizationId).pipe(
          map((org) => {
            return { ...employee, org: org };
          })
        )
      )
    );

    // 获取上级
    const parents$ = this.employeeService.getParents3(node.id).pipe(
      tap((parent) => console.log(parent)),
      switchMap((empRelations) =>
        empRelations.length === 0
          ? of([])
          : zip(
              ...empRelations.map((emp) =>
                this.employeeService.get8(emp.id?.parentId!)
              )
            )
      )
    );

    // 担任级别
    const levels$ = this.employeeService.getLevels(node.id).pipe(
      tap((sss) => console.log(sss)),
      switchMap((orgLevels: any) =>
        zip(
          ...orgLevels.map((orgLevel: any) =>
            this.orgService
              .get4(orgLevel.id.organizationLevelId.organizationId)
              .pipe(
                switchMap((org) =>
                  this.levelService
                    .get6(orgLevel.id.organizationLevelId.positionLevelId)
                    .pipe(
                      map((level) => {
                        return {
                          ...orgLevel,
                          org: org,
                          level: level,
                        };
                      })
                    )
                )
              )
          )
        )
      )
    );

    // 担任岗位
    const roles$ = this.employeeService.getRoles(node.id).pipe(
      tap((sss) => console.log(sss)),
      switchMap((orgRoles: any[]) =>
        orgRoles.length === 0
          ? of(orgRoles)
          : zip(
              ...orgRoles.map((orgRole: any) =>
                this.orgService
                  .get4(orgRole.id.organizationRoleId.organizationId)
                  .pipe(
                    switchMap((org) =>
                      this.roleService
                        .get3(orgRole.id.organizationRoleId.roleId)
                        .pipe(
                          map((role) => {
                            return {
                              ...orgRole,
                              org: org,
                              role: role,
                            };
                          })
                        )
                    )
                  )
              )
            )
      ),
      tap((ssss) => console.log(ssss))
    );

    employee$
      .pipe(
        tap((employee) => console.log(employee)),
        switchMap((employee: any) =>
          parents$.pipe(
            map((result) => {
              return { ...employee, parents: result };
            })
          )
        ),
        tap((employee) => console.log(employee)),
        switchMap((employee: any) =>
          roles$.pipe(
            map((result) => {
              return { ...employee, roles: result };
            })
          )
        ),
        tap((employee) => console.log(employee)),
        switchMap((employee: any) =>
          levels$.pipe(
            map((result) => {
              return { ...employee, levels: result };
            })
          )
        )
      )
      .subscribe((res) => {
        console.log(res);
        this.selectedEmployee = res;
      });
  }

  delelte() {
    // const ids$: any = this.checklistSelection.selected
    //   .filter((f) => !f.expandable)
    //   .map((s) => s.me.id);
    // this.employeeService.deleteBatch(ids$).subscribe(
    //   (res) => {
    //     // this.ngOnInit()
    //   },
    //   (err) => {
    //     console.log(err);
    //     this.message.create('error', '失败' + err.error.error);
    //   }
    // );
  }

  onClose(): void {
    console.log('tag was closed.');
  }

  onChange(value: string): void {
    console.log(value);
  }

  setModelPermission() {
    // this.router.navigateByUrl(
    //   this.router.createUrlTree([
    //     '/modelPermission',
    //     { ids: JSON.stringify(this.modelName?.split(',')) },
    //   ])
    // );
  }

  setDataPermission() {
    // console.log(this.selectListSelection.selected);
    // const dataIds$ = this.selectListSelection.selected.map((sel) => sel.me.id);
    // this.router.navigateByUrl(
    //   this.router.createUrlTree([
    //     '/dataPermission',
    //     {
    //       ids: JSON.stringify(this.modelName?.split(',')),
    //       dataIds: JSON.stringify(dataIds$),
    //     },
    //   ])
    // );
  }

  // for new organization

  isNewVisible: boolean = false;
  validateForm!: FormGroup;

  @ViewChild(OrganizationSearchComponent)
  organizationSearch!: OrganizationSearchComponent;
  submitForm() {
    if (!this.validateForm.valid) {
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      let role: Employee = this.validateForm.value;
      role.isRoot = true;
      role.organizationId = this.organizationSearch.selectedParent[0].id;
      this.employeeService.create8(role).subscribe((res) => {
        this.isNewVisible = false;
        // this.ngOnInit()
      });
    }
  }

  addNewOrganization() {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      code: [null, [Validators.required]],
      // parentId: [null, [Validators.required]],
      // root: [true, [Validators.required]],
    });
    this.isNewVisible = true;
  }

  // for set role
  isVisibleForSetRole: boolean = false;
  showSetRole() {
    this.isVisibleForSetRole = true;
  }

  @ViewChild(RoleSearchComponent) roleSearch!: RoleSearchComponent;
  handleOkForSetRole(): void {
    // console.log(
    //   'select org roles',
    //   this.roleSearch.selectListSelection.selected
    // );
    let empRoles: EmployeeOrganizationRole[] = [];
    // this.roleSearch.selectListSelection.selected.forEach((f) => {
    //   empRoles.push({
    //     stat: '1',
    //     id: {
    //       employeeId: this.selectListSelection.selected[0].me.id,
    //       organizationRoleId: {
    //         organizationId: f.id.organizationId,
    //         roleId: f.id.roleId,
    //       },
    //     },
    //   });
    // });

    // this.employeeService.saveRole(empRoles).subscribe((res) => {
    //   this.isNewVisible = false;
    //   this.ngOnInit();
    // });
    this.isVisibleForSetRole = false;
  }

  // for set level
  isVisibleForSetLevel: boolean = false;
  showSetLevel() {
    this.isVisibleForSetLevel = true;
  }

  @ViewChild(LevelSearchComponent) levelSearch!: LevelSearchComponent;
  handleOkForSetLevel(): void {
    // let empRoles: EmployeeOrganizationLevel[] = [];
    // this.levelSearch.selectListSelection.selected.forEach((f) => {
    //   empRoles.push({
    //     stat: '1',
    //     id: {
    //       employeeId: this.selectListSelection.selected[0].me.id,
    //       organizationLevelId: {
    //         organizationId: f.id.organizationId,
    //         positionLevelId: f.id.positionLevelId,
    //       },
    //     },
    //   });
    // });

    // this.employeeService.saveLevel(empRoles).subscribe((res) => {
    //   this.isVisibleForSetLevel = false;
    // });
  }

  isOrganizationEdit: boolean = false;
  showOrganizationEdit() {
    this.isOrganizationEdit = true;
  }

  handleOkForSetOrganization() {
    // this.employeeService
    //   .saveMasterOrganization(this.selectListSelection.selected[0].id,
    //       this.organizationSearch.selectedParent[0].id)
    //   .subscribe((res) => {});
  }

  isVisibleForSetReportManager = false;
  showSetReportManager() {
    this.isVisibleForSetReportManager = true;
  }

  @ViewChild(EmployeeSearchComponent) employeeSearch!: EmployeeSearchComponent;
  handleOkForSetReportManager() {
    // let employeeRelations: EmployeeRelation[] = [];
    // this.employeeSearch.selectListSelection.selected
    //   .map((a) => a.me.id)
    //   .forEach((f) => {
    //     employeeRelations.push({
    //       id: {
    //         employeeId: this.selectListSelection.selected[0].me.id,
    //         parentId: f,
    //       },
    //     });
    //   });
    // this.employeeService.saveRelations(employeeRelations).subscribe((res) => {
    //   this.isVisibleForSetReportManager = false;
    // });
  }

  isVisibleReportManagerTree = false;
  showReportManagerTree() {}

  isVisibleMyReportLine = false;

  @ViewChild(SetModelPermissionComponent)
  setModelPermissionComponent!: SetModelPermissionComponent;
  isVisibleForSetPermission: boolean = false;
  showSetPermissionModal() {
    this.isVisibleForSetPermission = true;
    setTimeout(() => {
      this.setModelPermissionComponent.models.push({
        name: this.modelName!,
        nameTxt: '菜单',
      });
    });
  }

  saveModelPermission() {
    this.setModelPermissionComponent.addPermission();
    this.isVisibleForSetPermission = false;
  }

  // data permission
  isVisibleForSetDataPermission: boolean = false;
  @ViewChild(SetDataPermissionComponent)
  setDataPermissionComponent!: SetDataPermissionComponent;
  showSetDataPermissionModal() {
    this.isVisibleForSetDataPermission = true;
    setTimeout(() => {
      // const dataIds$: any[] = this.selectListSelection.selected.map(sel => sel.me.id);
      // this.setDataPermissionComponent.dataIds = []
      // this.setDataPermissionComponent.dataIds.push(...dataIds$);
      // this.setDataPermissionComponent.models.push({ name: this.modelName!, nameTxt: "菜单" });
    });
  }

  saveDataPermission() {
    this.setDataPermissionComponent.addPermission();
    this.isVisibleForSetDataPermission = false;
  }

  handleCancel() {
    this.isNewVisible = false;
    this.isVisibleForSetLevel = false;
    this.isVisibleForSetRole = false;
    this.isOrganizationEdit = false;
    this.isVisibleForSetReportManager = false;
    this.isVisibleReportManagerTree = false;
    this.isVisibleMyReportLine = false;
    this.isVisibleForSetPermission = false;
    this.isVisibleForSetDataPermission = false;
  }
}
